const { Sequelize } = require('sequelize');
const dotenv = require('dotenv');

// 加载环境变量
dotenv.config();

// 数据库连接配置
const sequelize = new Sequelize(
    process.env.DB_NAME || 'recycle_clothes',
    process.env.DB_USER || 'root',
    process.env.DB_PASSWORD || 'root',
    {
        host: process.env.DB_HOST || 'localhost',
        port: parseInt(process.env.DB_PORT || '3306'),
        dialect: 'mysql',
        timezone: '+08:00',
        logging: process.env.NODE_ENV === 'development' ? console.log : false,
        define: {
            timestamps: true,
            paranoid: true,
            underscored: true,
            charset: 'utf8mb4',
            collate: 'utf8mb4_unicode_ci',
        },
        pool: {
            max: Math.max(1, parseInt(process.env.DB_POOL_MAX) || 5),
            min: Math.max(0, parseInt(process.env.DB_POOL_MIN) || 0),
            acquire: Math.max(30000, parseInt(process.env.DB_POOL_ACQUIRE) || 30000),
            idle: Math.max(10000, parseInt(process.env.DB_POOL_IDLE) || 10000)
        }
    }
);

// 测试数据库连接
async function testConnection() {
    try {
        await sequelize.authenticate();
        console.log('数据库连接成功');
    } catch (error) {
        console.error('数据库连接失败:', error);
        process.exit(1);
    }
}

testConnection();

module.exports = sequelize;